//
//  OrderEdit.m
//  iHedron
//
//  Created by George Radev on 2011-07-22.
//  Copyright 2011 I Me Mine. All rights reserved.
//

#import "OrderEdit.h"
#import "iHedronAppDelegate.h"
#import "OrderStockCell.h"
#import "OrderStockEdit.h"
#import "DatePicker.h"

@implementation OrderEdit
@synthesize updateMode;

+ (id)alloc{
	OrderEdit * instance = [super alloc];
	if(instance){
		[instance setEditedOrder:nil];
	}
    return instance;
}

-(void)setEditedOrder:(Order *) order{
	if(!order){
		updateMode = NO;
		editedOrder = [HedronCore getContextOrder];
	}else{
		updateMode = YES;
		[editedOrder release];
		editedOrder = order;
		[editedOrder retain];
	}
}
#pragma mark -
#pragma mark View lifecycle

- (void)viewDidLoad {
    [super viewDidLoad];

	self.title = @"Поръчка";
	if(!updateMode){
		UIBarButtonItem* leftButton = 
		[[UIBarButtonItem alloc] initWithTitle:@"Откажи" 
				style:UIBarButtonItemStylePlain target:self action:@selector(clearCurrentOrder)];
		self.navigationItem.leftBarButtonItem = leftButton;
		[leftButton release];
	}else {
		UIBarButtonItem* leftButton = 
		[[UIBarButtonItem alloc] initWithTitle:@"Назад" 
				style:UIBarButtonItemStylePlain target:self action:@selector(backCurrentOrder)];
		self.navigationItem.leftBarButtonItem = leftButton;
		[leftButton release];
	}

	UIBarButtonItem* rightButton = 
	[[UIBarButtonItem alloc] initWithTitle:@"Запиши" 
			style:UIBarButtonItemStyleDone target:self action:@selector(saveCurrentOrder)];
	self.navigationItem.rightBarButtonItem = rightButton;
	[rightButton release];
}

-(void)backCurrentOrder{
	[editedOrder reload];
	[HedronCore setCurrentEditableOrder:nil];
	[self.navigationController popViewControllerAnimated:TRUE];
}

-(void)clearCurrentOrder{
	alertMode = ALERT_CLEAR_MODE;
	UIAlertView *alert = [[UIAlertView alloc] init];
	[alert setTitle:@"Откажи!"];
	[alert setMessage:@"Желаете ли да откажете текущата поръчка?"];
	[alert setDelegate:self];
	[alert addButtonWithTitle:@"Да"];
	[alert addButtonWithTitle:@"Не"];
	[alert show];
	[alert release];
}

-(void)saveCurrentOrder{
	//check if client has been chosen.
	if(editedOrder.ocustomerid == 0){
		alertMode = ALERT_OK_MODE;
		UIAlertView *alert = [[UIAlertView alloc] init];
		[alert setTitle:@"Грешка!"];
		[alert setMessage:@"Моля, изберете клиент!"];
		[alert setDelegate:self];
		[alert addButtonWithTitle:@"Ok"];
		[alert show];
		[alert release];
		return;
	}
	
	//check if shipment date has been chosen.
	if(editedOrder.shipdate == 0){
		alertMode = ALERT_OK_MODE;
		UIAlertView *alert = [[UIAlertView alloc] init];
		[alert setTitle:@"Грешка!"];
		[alert setMessage:@"Моля, изберете дата на доставка!"];
		[alert setDelegate:self];
		[alert addButtonWithTitle:@"Ok"];
		[alert show];
		[alert release];
		return;
	}
	
	// check items
	if([editedOrder getStocksCount] <= 0){
		alertMode = ALERT_OK_MODE;
		UIAlertView *alert = [[UIAlertView alloc] init];
		[alert setTitle:@"Грешка!"];
		[alert setMessage:@"Моля, изберете продукти!"];
		[alert setDelegate:self];
		[alert addButtonWithTitle:@"Ok"];
		[alert show];
		[alert release];
		return;
	}
	
	alertMode = ALERT_SAVE_MODE;
	UIAlertView *alert = [[UIAlertView alloc] init];
	[alert setTitle:@"Запиши!"];
	[alert setMessage:@"Желаете ли да затворите и запишете текущата поръчка?"];
	[alert setDelegate:self];
	[alert addButtonWithTitle:@"Да"];
	[alert addButtonWithTitle:@"Не"];
	[alert show];
	[alert release];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
	if(alertMode == ALERT_SAVE_MODE && buttonIndex == 0){
		if ([editedOrder save] ) {
			if(updateMode){
				[HedronCore setCurrentEditableOrder:nil];
				[self.navigationController popViewControllerAnimated:TRUE];
			}else {		
				[editedOrder clear];
				[self.tableView reloadData];
			}
		}
		
	}else if(alertMode == ALERT_CLEAR_MODE && buttonIndex == 0){
		[editedOrder clear];
		[self.tableView reloadData];
		
	}else if(alertMode == ALERT_OK_MODE){
		[self.tableView reloadData];
	}
}

- (void)viewWillAppear:(BOOL)animated {
	[super viewWillAppear:animated];
	
	[editedOrder updateTotalAndClear];
	[self.tableView reloadData];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    return YES;
}

#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 2;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
	if (section == 0) {
		return 3;
	}else{
		long count = [editedOrder getStocksCount];
		return count + 1;
	}
    
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"Cell";
    
	int section = indexPath.section;
	int row = indexPath.row;

    // Configure the cell...
	if (section == 0) {
		UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
		if (cell == nil) {
			cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
		}
		
		if(row == 0){
			cell.textLabel.text = editedOrder.ocustomer;
			cell.textLabel.adjustsFontSizeToFitWidth = YES;
		}else if(row == 1){
			if(editedOrder.shipdate){
				NSString *dateString = [HedronCore dateFormat: editedOrder.shipdate];
				cell.textLabel.text = [NSString stringWithFormat:@"Доставка: %@", dateString];
				cell.textLabel.textAlignment = UITextAlignmentRight;
			}else{
				cell.textLabel.text = @"-- Изберете дата на доставка --";
			}
		}else if(row == 2){
			cell.textLabel.text = [NSString stringWithFormat:@"Total: %.2f", editedOrder.ototal];
			cell.textLabel.textAlignment = UITextAlignmentRight;
		}		
		return cell;
		
	}else{
		long count = [editedOrder getStocksCount];
		if (row < count) {
			static NSString *OrderStockCellIdentifier = @"OrderStockCell";
			
			OrderStockCell *cell = (OrderStockCell*)[tableView dequeueReusableCellWithIdentifier:OrderStockCellIdentifier];
			if (cell == nil) {
				NSArray* topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"OrderStockCell" owner:nil options:nil];
				
				for(id currentObject in topLevelObjects){
					if([currentObject isKindOfClass:[UITableViewCell class]]){
						cell = (OrderStockCell*) currentObject;
						break;
					}
				}
			}
			
			// Configure the cell...
			if(cell){
				Stock* stock = [editedOrder getStock: row ];
				cell.stockName.text = stock.sname;
				cell.stockQty.text = [NSString stringWithFormat: @"%d", stock.qty];
				cell.stockPrice.text = [NSString stringWithFormat: @"%.2f", stock.price];
			}
			return cell;
			
		}else{
			//create stock select row
			UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
			if (cell == nil) {
				cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
			}			
			cell.textLabel.text = @"-- изберете стока --";			
			return cell;
		}
	}
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 40;
}

-(UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UILabel* headerLabel = [[UILabel alloc] init];
    headerLabel.frame = CGRectMake(10, 0, 300, 40);
    headerLabel.backgroundColor = [UIColor clearColor];
	if (section == 0) {
		headerLabel.text = @"   Клиент";
	}else{
		headerLabel.text = @"   Стоки";
	}

	[headerLabel autorelease];
    return headerLabel;
}

#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    int section = indexPath.section;
	int row = indexPath.row;
	
	if (section == 0) {
		if(row == 0){
			// pick contact
			[self pickContact];
		}else if (row == 1){
			[self pickShipmentDate];
		}
		
	}else if(section == 1){
		long count = [editedOrder getStocksCount];
		if (count == row) {
			//switch to stock picker
			iHedronAppDelegate * delegate = (iHedronAppDelegate*)[[UIApplication sharedApplication] delegate];
			[delegate setTab: 0];
			
		}else{
			//open OrderStockEdit
			OrderStockEdit *orderStockEdit = [[OrderStockEdit alloc] initWithNibName:@"OrderStockEdit" bundle:nil];				
			[orderStockEdit setStock: [ [editedOrder getStocks] objectAtIndex: row]];
			[self.navigationController pushViewController:orderStockEdit animated:YES];
			[orderStockEdit release];
		}
	}
}


#pragma mark -
#pragma mark Memory management

- (void)dealloc {
	[HedronCore setCurrentEditableOrder:nil];
	[editedOrder release];
    [super dealloc];
}


#pragma mark Contact pick
-(void)pickContact {
	// creating the picker
	ABPeoplePickerNavigationController *picker = [[ABPeoplePickerNavigationController alloc] init];
	// place the delegate of the picker to the controll
	picker.peoplePickerDelegate = self;
	// showing the picker
	[self presentModalViewController:picker animated:YES];
	// releasing
	[picker release];
}

- (void)peoplePickerNavigationControllerDidCancel:(ABPeoplePickerNavigationController *)peoplePicker {
    // assigning control back to the main controller
	[self dismissModalViewControllerAnimated:YES];
}

- (BOOL)peoplePickerNavigationController: (ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person {
	
	ABRecordID recordId = ABRecordGetRecordID(person);
	if(recordId != kABRecordInvalidID){
		// setting the first name
		NSString* firstName = (NSString *)ABRecordCopyValue(person, kABPersonFirstNameProperty);
	
		// setting the last name
		NSString* lastName = (NSString *)ABRecordCopyValue(person, kABPersonLastNameProperty);	
	
		// setting the number
		editedOrder.ocustomerid = recordId;
		editedOrder.ocustomer = [NSString stringWithFormat: @"%@ %@", firstName, lastName];
		
		[firstName release];
		[lastName release];
		
		[self.tableView reloadData];
	}
	// remove the controller
    [self dismissModalViewControllerAnimated:YES];
	
    return NO;
}

- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier{
    return NO;
}

-(void)pickShipmentDate {
	DatePicker *datePicker = [[DatePicker alloc] initWithNibName:@"DatePicker" bundle:nil];		
	datePicker.date = [editedOrder shipdatePointer];
	
	[self.navigationController pushViewController:datePicker animated:YES];
	[datePicker release];
}

#pragma mark -


@end

